package com.cqq.common.core.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * <h3>Spring上下文工具类</h3>
 *
 * <p>
 * 从Spring上下文中获取定义的Bean
 * </p>
 * 
 * @author xijq
 * @version 1.0.0
 * 
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {

	private static ApplicationContext applicationContext;
	
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		SpringContextUtil.applicationContext = applicationContext;
	}

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}
	
	/**
	 * <h3>按上下文中定义Bean的id获取对象</h3>
	 * 
	 * @param <T> Bean的实例类
	 * @param name Bean的ID
	 * 
	 * @return Bean对象
	 * 
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) throws BeansException {
		return (T) applicationContext.getBean(name);
	}
	
	/**
	 * <h3>按上下文中定义Bean的Class类型获取对象</h3>
	 * 
	 * @param <T> Bean的实例类
	 * @param cls Bean的Class类型
	 * 
	 * @return Bean对象
	 * 
	 */
	public static <T> T getBean(Class<T> cls) throws BeansException {
		return (T) applicationContext.getBean(cls);
	}
}
